package com.ytktt.study.week3.task346.gateway;

import com.ytktt.study.week3.task346.gateway.inbound.HttpInboundServer;
import com.ytktt.study.week3.task346.gateway.properties.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.Arrays;
import java.util.List;

@Slf4j
@SpringBootApplication
@EnableConfigurationProperties({ApplicationProperties.class})
public class NettyServerApplication implements ApplicationRunner {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private HttpInboundServer httpInboundServer;

    public static void main(String[] args) {
        SpringApplication.run(NettyServerApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String proxyPort = System.getProperty("proxyPort");
        int port;
        if (StringUtils.isBlank(proxyPort)) {
            port = this.applicationProperties.getPort();
        } else {
            port = Integer.parseInt(proxyPort);
        }
        // 这是之前的单个后端url的例子
//        String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
//          //  http://localhost:8888/api/hello  ==> gateway API
//          //  http://localhost:8088/api/hello  ==> backend service
        // java -Xmx512m gateway-server-0.0.1-SNAPSHOT.jar  #作为后端服务


        // 这是多个后端url走随机路由的例子
        List<String> proxyServers;
        String sysConfigProxyServers = System.getProperty("proxyServers");
        if (StringUtils.isNotBlank(sysConfigProxyServers)) {
            proxyServers = Arrays.asList(sysConfigProxyServers.split(","));
        } else {
            proxyServers = this.applicationProperties.getProxyServers();
        }

        log.info("{} {} starting...", this.applicationProperties.getName(), this.applicationProperties.getVersion());
        try {
            this.httpInboundServer.run(port);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
